#include "app_message.h"

char *app_message_bytes2json(char *bytes_data, int bytes_len)
{
    // 1 从字节数组中拆解数据
    char conn_type = bytes_data[0]; // 连接类型
    char id[bytes_data[1]];
    char msg[bytes_data[2]];
    int id_len = bytes_data[1];
    int msg_len = bytes_data[2];
    memcpy(id, bytes_data + 3, id_len);
    memcpy(msg, bytes_data + 3 + id_len, msg_len);

    char *id_hexstr = app_common_bytes2hexstr(id, id_len);
    char *msg_hexstr = app_common_bytes2hexstr(msg, msg_len);

    // 把对应的数值组合为一个json字符串
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hexstr);
    cJSON_AddStringToObject(root, "msg", msg_hexstr);

    char *json_str = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return json_str;
}

int app_message_json2bytes(char *json_str,char *bytes_buff,int buff_len)
{
    // 1 先从json中提取数值
    cJSON *root = cJSON_Parse(json_str);
    if (root == NULL)
    {
        log_error("json parse error\n");
        return -1;
    }
    cJSON *conn_type_cJson = cJSON_GetObjectItem(root, "conn_type");
    cJSON *id_cJson = cJSON_GetObjectItem(root, "id");
    cJSON *msg_cJson = cJSON_GetObjectItem(root, "msg");
    if (conn_type_cJson == NULL || id_cJson == NULL || msg_cJson == NULL)
    {
        log_error("json parse error\n");
        return -1;
    }

    char conn_type =  conn_type_cJson->valueint;
    char *id = id_cJson->valuestring;
    char *msg = msg_cJson->valuestring;

    char id_bytes[strlen(id)/2];
    char msg_bytes[strlen(msg)/2];
    app_common_hexstr2bytes(id,id_bytes);
    app_common_hexstr2bytes(msg,msg_bytes);

    int len = 3 + strlen(id)/2 + strlen(msg)/2;
    if (buff_len < (3 + strlen(id)/2 + strlen(msg)/2))
    {
        log_error("buff_len is too small( %d )\n",len);
        return -1;
    }
    buff_len = len;
    bytes_buff[0] = conn_type;
    bytes_buff[1] = strlen(id)/2;
    bytes_buff[2] = strlen(msg)/2;
    memcpy(bytes_buff+3,id_bytes,strlen(id)/2);
    memcpy(bytes_buff+3+strlen(id)/2,msg_bytes,strlen(msg)/2);

    return len;
    
}